<?php

namespace app\api\controller;

use addons\third\model\Third;
use app\common\controller\Api;
use app\common\model\User;
use think\Log;

/**
 * 登陆接口
 */
class Login extends Api
{
    protected $noNeedLogin = ['userInfoAuth', 'getUserByCode'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    public function getUserByCode()
    {
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        if (!$platform) {
            $this->error(__('Parameter %s can not be empty', 'platform'));
        }
        if (!$code) {
            $this->error(__('Parameter %s can not be empty', 'code'));
        }
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result['code'] == 0) {
            $auth = \app\common\library\Auth::instance();
            $auth->keeptime(0);
            $third = Third::get(['platform' => $platform, 'openid' => $result['data']['openid']], 'user');
            if ($third) {
                if (!$third->user) {
                    $third->delete();
                    $this->success(__('User not found'), null, 99999);
                } else {
                    $third->allowField(true)->save($result['data']);
                    // 写入登录Cookies和Token
                    $auth->direct($third->user_id);
                }
                $user = $this->auth->getUserinfo();
                $user['ruleList'] = $this->auth->getRuleList();
                $data = [
                    'userinfo'  => $user,
                    'thirdinfo' => $result
                ];
                // 添加用户访问记录
                $accessLog = model('\app\admin\model\jy\UserAccessLog')->where(['user_id' => $this->auth->id, 'create_time' => ['>=', date("Y-m-d", time())]])->find();
                if ($accessLog) {
                    $accessLog->isUpdate(true)->save(['update_time' => date("Y-m-d H:i:s", time())]);
                } else {
                    model('\app\admin\model\jy\UserAccessLog')->insert(['user_id' => $this->auth->id, 'update_time' => date("Y-m-d H:i:s", time())]);
                }
                $this->success(__('Logged in successful'), $data);
            }
            $this->success(__('User not found'), null, 99999);
        }
        $this->error($result['msg'], null, $result['code']);
    }

    /**
     * 用户授权接口
     */
    public function userInfoAuth()
    {
        $platform = $this->request->post("platform");
        $encryptedData = $this->request->post("encryptedData");
        $iv = $this->request->post("iv");
        $code = $this->request->post("code");
        $inviteId = $this->request->post("inviteId");
        $inviteType = $this->request->post("inviteType");
        if (!$platform) {
            $this->error(__('Parameter %s can not be empty', 'platform'));
        }
        if (!$code) {
            $this->error(__('Parameter %s can not be empty', 'code'));
        }
        if (!$encryptedData) {
            $this->error(__('Parameter %s can not be empty', 'encryptedData'));
        }
        if (!$iv) {
            $this->error(__('Parameter %s can not be empty', 'iv'));
        }
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->decryptData(['code' => $code, 'encryptedData' => $encryptedData, 'iv' => $iv]);
        if ($result['code'] == 100) {
            $result['openid'] = $result['data']['openId'];
            $result['nickname'] = $result['data']['data']['nickName'];
            $result['session_key'] = $result['data']['sessionKey'];
            $result['refresh_token'] = isset($result['data']['refresh_token']) ? $result['data']['refresh_token'] : '';
            $result['access_token'] = $result['data']['access_token'];
            $result['expires_in'] = $result['data']['expires_in'];
            $result['avatar'] = $result['data']['data']['avatarUrl'];

            $loginRet = \addons\third\library\Service::connect($platform, $result, ['invite_id' => $inviteId]);
            if ($loginRet) {
                $user = $this->auth->getUserinfo();
                $user['ruleList'] = $this->auth->getRuleList();
                $data = [
                    'userinfo'  => $user,
                    'thirdinfo' => $result
                ];
                // 邀请记录
                if ($inviteId && $inviteType) {
                    $userInvite = model('app\admin\model\jy\UserInvite')->where(['user_id' => $this->auth->id])->find();
                    if (!$userInvite) {
                        $userInvite['user_id'] = $this->auth->id;
                        $userInvite['invite_user_id'] = $inviteId;
                        $userInvite['invite_type'] = $inviteType ? $inviteType : 1;
                        $userInvite['update_time'] = date("Y-m-d H:i:s", time());
                        model('app\admin\model\jy\UserInvite')->insert($userInvite);
                    }
                }
                // 添加用户访问记录
                $accessLog = model('\app\admin\model\jy\UserAccessLog')->where(['user_id' => $this->auth->id, 'create_time' => ['>=', date("Y-m-d", time())]])->find();
                if ($accessLog) {
                    $accessLog->isUpdate(true)->save(['update_time' => date("Y-m-d H:i:s", time())]);
                } else {
                    model('\app\admin\model\jy\UserAccessLog')->insert(['user_id' => $this->auth->id, 'update_time' => date("Y-m-d H:i:s", time())]);
                }
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error($result['msg'], null, $result['code']);
    }

    public function phoneAuth()
    {
        $platform = $this->request->post("platform");
        $encryptedData = $this->request->post("encryptedData");
        $iv = $this->request->post("iv");
        $code = $this->request->post("code");
        if (!$platform) {
            $this->error(__('Parameter %s can not be empty', 'platform'));
        }
        if (!$encryptedData) {
            $this->error(__('Parameter %s can not be empty', 'encryptedData'));
        }
        if (!$iv) {
            $this->error(__('Parameter %s can not be empty', 'iv'));
        }
        if (!$code) {
            $this->error(__('Parameter %s can not be empty', 'code'));
        }
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->decryptData(['code' => $code, 'encryptedData' => $encryptedData, 'iv' => $iv]);
        if ($result['code'] == 100) {
//            Log::record('[ LOG ] $result =' . json_encode($result, JSON_UNESCAPED_UNICODE), 'info');
            $mobile = $result['data']['data']['phoneNumber'];
            if ($mobile) {
                $user = User::getByMobile($mobile);
                if ($user && ($user['id'] != $this->auth->id)) {
                    $this->error('Mobile already exist');
                }
            }
            $user = $this->auth->getUser();
            if (!$user) {
                $this->error(__('User not found'));
            }
            $user->save(['mobile' => $mobile]);
            $userInfo = $this->auth->getUserinfo();
            $userInfo['ruleList'] = $this->auth->getRuleList();
            $data = [
                'userinfo'  => $userInfo,
                'thirdinfo' => ''
            ];
            $this->success(__('Logged in successful'), $data);
        }
        $this->error($result['msg'], null, $result['code']);
    }
}
